package com.ruoyi.tplus.service.imp;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.ruoyi.common.annotation.DataSource;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.DataSourceType;
import com.ruoyi.tplus.Vars.ConstantsDanju;
import com.ruoyi.tplus.Vars.OrderMap;
import com.ruoyi.tplus.domain.*;
import com.ruoyi.tplus.mapper.ITPlusMapper;
import com.ruoyi.tplus.service.ITPlusService;
import org.apache.poi.ss.formula.functions.T;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;


@Service
@DataSource(DataSourceType.SLAVE)
public class TPlusServiceImp implements ITPlusService {
    private static final Logger LOGGER = LoggerFactory.getLogger(TPlusServiceImp.class);
    @Autowired
    private ITPlusMapper  tplusMapper;



    @Override
    public Map insertOrUpdateXhd(String data) {
        JSONObject entries = JSONUtil.parseObj(data);
        Object dataO = entries.get("data");
        JSONObject jsonData = JSONUtil.parseObj(dataO);
        TPlusXhd tPlusXhd = jsonData.toBean(TPlusXhd.class);
        List<TPlusXhdS> entity = tPlusXhd.getEntity();
        tPlusXhd.setEntity(entity);
        //查询是否存在对应 的销货单
        TPlusXhd xhdFromDb = tplusMapper.queryXhdCode(tPlusXhd);
        if(xhdFromDb != null && xhdFromDb.getId() > 0){
            LOGGER.info("销货单单号：{}重复，不允许保存",xhdFromDb.getCode());
        }else {
            int count = tplusMapper.insertXhd(tPlusXhd);

            if(entity != null && entity.size() > 0){
                for (int i = 0; i < entity.size(); i++) {
                    entity.get(i).setIdSaleDeliveryDTO(tPlusXhd.getId());
                    //设置存货id
                    AA_Inventory inventory = tplusMapper.queryInventoryIdByCode(entity.get(i));
                    if (inventory != null){
                        entity.get(i).setS_idinventory(inventory.getId());

                    }else {
                        LOGGER.info("存货编码：{}不存在",entity.get(i).getS_partnerinventorycode());
                        return null;
                    }

                    //设置单位id
                    AA_Unit unit = tplusMapper.queryAA_UnitIdByCode(entity.get(i));
                    entity.get(i).setIdbaseunit(unit.getId());
                    int son = tplusMapper.insertXhdS(entity.get(i));
                }
            }
        }
        return null;
    }

    @Override
    @Transactional
    public Map insertOrUpdateJhd(String data) {

        JSONObject entries = JSONUtil.parseObj(data);
        Object dataO = entries.get("data");
        JSONObject jsonData = JSONUtil.parseObj(dataO);
        TPlus_Jhd tPlusJhd = new TPlus_Jhd();
        tPlusJhd = jsonData.toBean(TPlus_Jhd.class);
        List<TPlus_JhdS> entity = tPlusJhd.getEntity();
        tPlusJhd.setEntity(entity);
        //查询是否存在对应 的销货单
        TPlus_Jhd tPlusJhdDb = tplusMapper.queryJhdCode(tPlusJhd);
        if(tPlusJhdDb != null ){
            LOGGER.info("进货单单号：{}重复，不允许保存",tPlusJhdDb.getCode());
        }else {
            //1、设置业务类型编码
            if (tPlusJhd.getBusinessTypeName() != null && !"".equals(tPlusJhd.getBusinessTypeName())){
                tPlusJhd.setIdbusinesstype(Integer.parseInt(OrderMap.getBusinessType().get(tPlusJhd.getBusinessTypeName())));
            }else {
                tPlusJhd.setIdbusinesstype(1);
            }

            //2、设置票据类型
            if (tPlusJhd.getInvoicetypename() != null && !"".equals(tPlusJhd.getInvoicetypename())){
                tPlusJhd.setInvoicetypeid(Integer.parseInt(OrderMap.getInvoiceType().get(tPlusJhd.getInvoicetypename())));
            }

            //3、设置供应商编码
            AA_Partner partner = tplusMapper.queryPartnerIdByName(tPlusJhd.getPartnername());
            tPlusJhd.setIdpartner(partner.getId());
            //4、设置付款方式(既然不需要，就在Domain值给默认值了)
//            tPlusJhd.setPayTypeId(orderMap.getPayTypee().get(tPlusJhd.getPayTypeName()));

            tplusMapper.insertJhd(tPlusJhd);
            LOGGER.info("进货单单据号：{},表头主键：{}",tPlusJhd.getCode(),tPlusJhd.getId());
            if(entity != null && entity.size() > 0){
                for (int i = 0; i < entity.size(); i++) {
                    TPlus_JhdS tPlusJhdS = entity.get(i);
                    //1、设置表头关联ID
                    tPlusJhdS.setIdpurchasearrivaldto(tPlusJhd.getId());
                    //2、设置仓库id
                    AA_Warehouse warehouse = tplusMapper.queryAA_WarehouseIdByCode(tPlusJhd.getWarehousecode());
                    if (warehouse == null){
                        LOGGER.info("仓库编码：{}不存在",tPlusJhd.getWarehousecode());
                        return null;
                    }
                    tPlusJhdS.setIdwarehouse(warehouse.getId());
                    //3、设置存货id
                    AA_Inventory inventory = tplusMapper.queryInventoryIdByName(tPlusJhdS.getDetailsinventoryname());
                    if (inventory != null){
                        entity.get(i).setIdinventory(inventory.getId());
                    }else {
                        LOGGER.info("商品：{}不存在",tPlusJhdS.getDetailsinventoryname());
                        return null;
                    }

                    //设置商品单位id
                    AA_Unit unit = tplusMapper.queryAA_UnitIdByName(tPlusJhdS.getDetailsunitname());
                    if (unit == null){
                        LOGGER.info("商品单位：{}不存在",tPlusJhdS.getDetailsunitname());
                        return null;
                    }
                    tPlusJhdS.setIdunit(unit.getId());

                    tplusMapper.insertJhdS(tPlusJhdS);
                    LOGGER.info("进货单单据号:{},子表id：{}",tPlusJhd.getCode(),tPlusJhdS.getId());
                }
            }
        }
        return null;
    }

    /**
     * 材料出库单
     * @param temp
     * @return
     */
    @Override
    public Map insertOrUpdateClckd(String temp) {



        JSONObject jsonData = doSomething( temp);
        ST_RDRecord stRdRecord = jsonData.toBean(ST_RDRecord.class);
        //1、根据部门名称查询id(AA_department):SELECT * FROM AA_Department WHERE NAME = '销售中心公用项目'
        /**
         * 验证单据是否已经存在
         */
        int count = tplusMapper.queryClckdCode(stRdRecord);
        if (count > 0){
            LOGGER.info("材料出库单单号：{}重复，不允许保存",stRdRecord.getCode());
            return Collections.emptyMap();
        }
        //TODO
        String dept = "机械部"; JSONUtil.parseObj(stRdRecord.getDepartment()).get("name").toString();
        AA_Department department = tplusMapper.queryAA_DepartmentIdByName(dept);
        stRdRecord.setIddepartment(department.getId());
        //2、根据业务类型名称查询id(AA_BusiType):SELECT * FROM AA_BusiType WHERE Name IN('直接领料','直接退料'),前台添加了对应 的id映射


        //3、根据存货名称查询id(AA_Inventory):SELECT * FROM AA_Inventory WHERE Name = '材料'
        List<ST_RDRecord_b> listStRdRecordB = stRdRecord.getEntity();
        //4、根据[单位名称]查询id(AA_Unit):SELECT * FROM AA_Unit WHERE NAME = '个'
        //5、根据[仓库名称]查询id(AA_Warehouse):SELECT * FROM AA_Warehouse WHERE NAME = '材料库'
        AA_Warehouse warehouse = tplusMapper.queryAA_WarehouseIdByName(stRdRecord.getWarehouse());
        stRdRecord.setIdwarehouse(warehouse.getId());
        int headCount = tplusMapper.insertClckd(stRdRecord);
        for (int i = 0; i < listStRdRecordB.size(); i++) {
            String inventoryName = listStRdRecordB.get(i).getInventory();
            AA_Inventory inventory = tplusMapper.queryInventoryIdByName(inventoryName);
            listStRdRecordB.get(i).setIdinventory(inventory.getId());//设置存货id
            listStRdRecordB.get(i).setIdunit(inventory.getIdUnit());//设置单位id
            warehouse = tplusMapper.queryAA_WarehouseIdByName(listStRdRecordB.get(i).getSwarehouse());

            LOGGER.info(listStRdRecordB.get(i).getSwarehouse());
            LOGGER.info(warehouse.getId() + "");
            listStRdRecordB.get(i).setIdSwarehouse(warehouse.getId());//设置仓库id
            listStRdRecordB.get(i).setIdRDRecordDTO(stRdRecord.getId());//设置部门id
            int bodyCount = tplusMapper.insertClckdS(listStRdRecordB.get(i));
            LOGGER.info("材料出库单表头id：{},子表id:{}",stRdRecord.getId(),listStRdRecordB.get(i).getId());
        }



        return Collections.emptyMap();
    }

    @Override
    @Transactional
    public Map insertOrUpdateReceiptAndPayment(String temp) {
        JSONObject entries = JSONUtil.parseObj(temp);
        Object dataO = entries.get("data");
        JSONObject jsonData = JSONUtil.parseObj(dataO);
        ARAP_ReceivePayment receivePayment = new ARAP_ReceivePayment();
        receivePayment = jsonData.toBean(ARAP_ReceivePayment.class);
        List<ARAP_ReceivePayment_MultiSettle> entity = receivePayment.getEntity();
        receivePayment.setEntity(entity);
        //查询是否存在对应 的收款、付款单
        ARAP_ReceivePayment receivePaymentDb = tplusMapper.queryReceiptAndPaymentCode(receivePayment.getCode());
        if(receivePaymentDb != null ){
            LOGGER.info("收款单/付款单 单号：{}重复，不允许保存",receivePaymentDb.getCode());
        }else {
            //1、设置业务类型id:79、80
            /*
            固定：直接前台固定值传输过来
            if (receivePayment.getBusitype() != null && !"".equals(receivePayment.getBusitype())){
                    receivePayment.setIdbusitype(Integer.parseInt(orderMap.getReceiveAndPayBusiType().get(receivePayment.getBusitype())));
            }else {
                LOGGER.info("单据号：{}单据类型：{}不存在",receivePayment.getCode(),receivePayment.getBusitype());
                return AjaxResult.error();
            }

            */
            receivePayment.setIdbusitype(80);
            //2、设置部门iddepartment 放到子表中映射到表头
            AA_Department department = tplusMapper.queryAA_DepartmentIdByName(receivePayment.getDepartment().get("name").toString());
            if (department != null){
                receivePayment.setIddepartment(department.getId());
            }else {
                LOGGER.info("单据号：{}部门名称：{}不存在",receivePayment.getCode(),receivePayment.getDepartment());
                return AjaxResult.error("");
            }

            //3、设置结算客户（往来客户）
            if(entity != null && entity.size() > 0){
                String partnername = entity.get(0).getPartnername();
                receivePayment.setIdpartner(59);
//                AA_Partner partner = tplusMapper.queryPartnerIdByName(partnername);
//                if (partner != null){
//                    receivePayment.setIdpartner(partner.getId());
//                }
            }

            //4、设置付款公司

            //4、业务员（不是必填项）
//            AA_Person person = tplusMapper.queryAA_personIdByName(receivePayment.getPersoninfo().get("name"));
//            if (person != null){
//                receivePayment.setIdperson(person.getId());
//            }else {
//                LOGGER.info("单据号：{}业务员名称：{}不存在",receivePayment.getCode(),receivePayment.getPersoninfo().get("name"));
//                return AjaxResult.error();
//            }
            //5、设置结算方式 固定 ：现金
            /*if (receivePayment.getNamesettlestyle() != null && !"".equals(receivePayment.getNamesettlestyle())){
                AA_SettleStyle settleStyle = tplusMapper.queryAA_SettleStyleIdByName(receivePayment.getNamesettlestyle());
                    receivePayment.setIdSettleStyle(settleStyle.getId());
            }else {
                LOGGER.info("单据号：{}结算方式名称：{}不存在",receivePayment.getCode(),receivePayment.getNamesettlestyle());
                return AjaxResult.error();
            }*/
            if (OrderMap.settleStyle == null || OrderMap.settleStyle.trim().isEmpty()) {
                OrderMap.settleStyle = "1"; // 设置默认值
            }
            receivePayment.setIdSettleStyle(Integer.parseInt(OrderMap.settleStyle));
            //6、设置结算账号
            AA_BankAccount bankAccount = tplusMapper.queryAA_BankAccountIdByName(receivePayment.getNamebankaccount());
            if (bankAccount != null){
                receivePayment.setIdBankAccount(bankAccount.getId());
            }else {
                LOGGER.info("单据号：{}结算账号名称：{}不存在",receivePayment.getCode(),receivePayment.getNamebankaccount());
//                return AjaxResult.error();
            }

            tplusMapper.insertReceiptAndPayment(receivePayment);
            LOGGER.info("付款单单据号：{},表头主键：{}",receivePayment.getCode(),receivePayment.getId());
            if(entity != null && entity.size() > 0){
                for (int i = 0; i < entity.size(); i++) {
                    ARAP_ReceivePayment_MultiSettle receivePaymentSon = entity.get(i);
                    //1、设置表头关联ID
                    receivePaymentSon.setIdArapReceivePaymentDTO(receivePayment.getId());
                    //2、设置code
                    receivePaymentSon.setCode(String.format("%04d",  i));
                    receivePaymentSon.setOrigAmountSon(receivePaymentSon.getAmountson());
                    receivePaymentSon.setAmountson(receivePaymentSon.getAmountson());
//                    receivePaymentSon.setIdbankaccount(receivePayment.getIdBankAccount());
                    //3、设置数量
//                    receivePaymentSon.setOrigAmountSon(receivePaymentSon.getAmountson());
//                    receivePaymentSon.setAmountson(receivePayment.getAmount());
                    //4、设置idbankaccount
                    AA_BankAccount bankAccountSon = tplusMapper.queryAA_BankAccountIdByName(receivePayment.getNamebankaccount());
                    if(bankAccountSon != null){
                        receivePaymentSon.setIdbankaccount(bankAccountSon.getId());
                    }else{
                        LOGGER.info("单据号：{}的 结算账号名称：{}不存在",receivePaymentSon.getCode(),receivePayment.getNamebankaccount());
                    }

                    //5、设置idsettlestyle
//                    AA_SettleStyle settleStyleSon = tplusMapper.queryAA_SettleStyleIdByName(OrderMap.idSettleStyleMoney);
                    receivePaymentSon.setIdsettlestyle(Integer.parseInt(OrderMap.settleStyle != null ? OrderMap.settleStyle : "1"));
                    //6、设置折扣
                    receivePaymentSon.setAllowances(receivePayment.getAllowances());
                    receivePaymentSon.setOrigAllowances(receivePayment.getAllowances());
                    //7、设置子表账号名称
                    System.out.println(receivePayment);
                    receivePaymentSon.setIdbankaccount(receivePayment.getIdBankAccount());
                    receivePaymentSon.setDocumentcode("123");
                    tplusMapper.insertReceiptAndPaymentS(receivePaymentSon);
                    LOGGER.info("付款、收款单：{},子表头主键：{}",receivePayment.getCode(),receivePaymentSon.getId());
                }
            }
        }
        return AjaxResult.success();

    }



    protected JSONObject doSomething( String data) {

        JSONObject entries = JSONUtil.parseObj(data);
        Object dataO = entries.get("data");
        JSONObject jsonData = JSONUtil.parseObj(dataO);
        return jsonData;
    }

}
